package cn.ezios.huo.s3.old;

import cn.ezios.huo.s3.old.file.S3StorageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;

import java.util.concurrent.ExecutorService;

/**
 *
 */
@Slf4j
@Component
public class S3AsyncStorageClient implements StorageClient {

    private final S3AsyncClient client;

    private final ExecutorService es;

    public S3AsyncStorageClient(S3AsyncClient client, @Qualifier("virtualThreadExecutorService") ExecutorService es) {
        this.client = client;
        this.es = es;
    }

    @Override
    public void upload(S3StorageDTO storageDTO) {
        AsyncRequestBody requestBody = AsyncRequestBody.fromInputStream(builder -> {
            builder.contentLength(storageDTO.getSize());
            builder.inputStream(storageDTO.getInputStream());
            builder.executor(es);
        });
        client.putObject(req -> {
                    req.bucket(storageDTO.getBucket()).key((storageDTO.getDir()==null?"":storageDTO.getDir() + "/") + storageDTO.getFileName()).build();
                }, requestBody)
                .thenAccept(resp -> log.info("上传成功：{}", resp))
                .join();

    }
}
